package com.lyl.security.filter;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.lyl.security.dto.LoginDetails;
import com.lyl.security.utils.JwtUtil;
import com.lyl.security.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr.Luo
 * @date 2022-09-19 14:53
 * @desc JwtToken认证过滤器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        LoginDetails loginDetails = getLoginDetails(request);
        if (ObjectUtil.isNotEmpty(loginDetails) && ObjectUtil.isEmpty(SecurityContextHolder.getContext().getAuthentication())) {
            //tokenService.verifyToken(loginDetails);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDetails.getUsername(), loginDetails.getPassword(), loginDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }

    public LoginDetails getLoginDetails(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (CharSequenceUtil.isNotBlank(token)) {
            //1. 验证token
            String tokenKey = JwtUtil.parseToken(token);
            //2. 获取redis中用户信息
            Object obj = RedisUtil.get("login_token:" + tokenKey);
            if (ObjectUtil.isNotEmpty(obj)) {
                return JSONUtil.toBean(JSONUtil.toJsonStr(obj), LoginDetails.class);
            }
        }
        return null;
    }
}
